package com.thinksns.sociax.t4.android.topic;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.thinksns.sociax.android.R;
import com.thinksns.sociax.api.Api;
import com.thinksns.sociax.component.CustomTitle;
import com.thinksns.sociax.component.LeftAndRightTitle;
import com.thinksns.sociax.modle.RecentTopic;
import com.thinksns.sociax.t4.android.ThinksnsAbscractActivity;
import com.thinksns.sociax.t4.android.video.ToastUtils;
import com.thinksns.sociax.t4.model.ModelTopic;
import com.thinksns.sociax.thinksnsbase.exception.ApiException;
import com.thinksns.sociax.thinksnsbase.network.ApiHttpClient;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 类说明：推荐话题
 *
 * @version 1.0
 * @date Jan 18, 2013
 */
public class AtTopicActivity extends ThinksnsAbscractActivity {

    private ListView lvSearch;
    private EditText edtSearch;
    private RelativeLayout rlSearch;
    private TopicAdapter topicAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //4.5版本话题搜索
        lvSearch = (ListView) findViewById(R.id.lv_search);
        edtSearch = (EditText) findViewById(R.id.input_search_query);
        rlSearch = (RelativeLayout) findViewById(R.id.searchBarContainer);
        rlSearch.setVisibility(View.VISIBLE);
        topicAdapter = new TopicAdapter(this, null);
        lvSearch.setAdapter(topicAdapter);


        lvSearch.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ModelTopic m = (ModelTopic) topicAdapter.getItem(position);
                RecentTopic recentTopic = new RecentTopic();
                recentTopic.setTopic_id(m.getTopic_id());
                recentTopic.setName(m.getTopic_name());
                EventBus.getDefault().post(recentTopic);
                setResult(m.getTopic_name());
            }
        });
        edtSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String tem = edtSearch.getText().toString();
                if (tem.length() == 0) {
                    lvSearch.setVisibility(View.GONE);
                    ((InputMethodManager) edtSearch.getContext().getSystemService(Context.INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(AtTopicActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                } else {
                    try {
                        new Api.WeibaApi().search_Topic(tem, new ApiHttpClient.HttpResponseListener() {
                            @Override
                            public void onSuccess(Object result) {
                                if (result == null) {
                                    return;
                                }
                                String tem = (String) result;
                                try {
                                    List<ModelTopic> search_topic = new ArrayList<ModelTopic>();
                                    JSONArray topic = new JSONArray(tem);
                                    for (int i = 0; i < topic.length(); i++) {
                                        JSONObject js = (JSONObject) topic.get(i);
                                        ModelTopic m = new ModelTopic();
                                        m.setTopic_id(js.getInt("topic_id"));
                                        m.setTopic_name(js.getString("topic_name"));
                                        search_topic.add(m);
                                    }
                                    if (search_topic.size() == 0) {
                                        lvSearch.setVisibility(View.GONE);
                                        ToastUtils.showToast(AtTopicActivity.this, "暂无搜索结果");
                                    } else {
                                        lvSearch.setVisibility(View.VISIBLE);
                                    }
                                    topicAdapter.refresh(search_topic);

                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }


                            }

                            @Override
                            public void onError(Object result) {

                            }
                        });
                    } catch (ApiException e) {
                        e.printStackTrace();
                    }

                }


            }
        });
        edtSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if(actionId == EditorInfo.IME_ACTION_GO){
                    setResult(edtSearch.getText().toString());
                }
                return false;
            }
        });

        FragmentRecommendTopicList fragment = FragmentRecommendTopicList.newInstance();
        fragmentTransaction.replace(R.id.ll_content, fragment)
                .commit();

    }

    @Override
    public String getTitleCenter() {
        return getString(R.string.topic_title);
    }

    @Override
    protected CustomTitle setCustomTitle() {
        return new LeftAndRightTitle(R.drawable.img_back, this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_common;
    }

    /**
     * 选择话题回传给上一个页面
     *
     * @param topic_name 话题名称
     */
    public void setResult(String topic_name) {
        Intent intent = new Intent();
        intent.putExtra("recent_topic", topic_name);
        setResult(RESULT_OK, intent);
        finish();
    }
}
